const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');

exports.authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ status: 401, msg: '未提供访问令牌' });
  }

  jwt.verify(token, secret, (err, decoded) => {
    if (err) {
      return res.status(403).json({ status: 403, msg: '令牌无效' });
    }
    req.userId = decoded.userId;
    next();
  });
};
